<template>
    <el-form :model="formParam" :rules="rules" ref="custForm">
        <el-table :data="portInfoFormObj.recordData" class="detail-table" :span-method="arraySpanMethod" stripe :border="true">
            <el-table-column prop="name" label="" width="140" />
            <el-table-column prop="DATE" label="DATE">
                <template #default="scope">
                    <el-form-item v-if="scope.$index==0" prop="rampDownTime">
                        <el-date-picker type="datetime" format="YYYY/MM/DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                            v-model="formParam.rampDownTime" placeholder="Please select" />
                    </el-form-item>
                    <el-form-item v-if="scope.$index==3" prop="rampUpTime">
                        <el-date-picker type="datetime" format="YYYY/MM/DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                            v-model="formParam.rampUpTime" placeholder="Please select" />
                    </el-form-item>
                    <div v-if="scope.$index==5" style="display: flex;align-items: center;">  
                        <DragUpload
                        :multiple="false"
                        accept=".pdf,.docx,.xlsx,.doc,.docx,.txt,.zip,.rar"
                        :maxSize="1"
                        :disabled="!hasTableEditAuth('schedule:general:edit')"
                        @files-change="handleVoyageSofFilesChange"
                        @file-removed="handleFileRemoved($event,0)"
                        v-model="voyageSof"
                        />
                    </div>
                    <div v-if="scope.$index==6" style="display: flex;align-items: center;" >
                        <DragUpload  
                        :multiple="true"
                        accept=".pdf,.docx,.xlsx,.doc,.docx,.txt,.zip,.rar"
                        :maxSize="5"
                        :disabled="!hasTableEditAuth('schedule:portOperation:edit')"
                        @files-change="handleDamageReportFilesChange"
                        @file-removed="handleFileRemoved($event,1)"
                        v-model="damageReport"
                        /> 
                    </div>    
                    
                </template>
            </el-table-column>
            <el-table-column prop="ANCHORAGE" label="TIME COMMS">
                <template #default="scope">
                    <el-form-item v-if="scope.$index==1" prop="loadingTimeComms">
                        <el-date-picker type="datetime" format="YYYY/MM/DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                            v-model="formParam.loadingTimeComms" placeholder="Please select" />
                    </el-form-item>
                    <el-form-item v-if="scope.$index==2" prop="dischargingTimeComms">
                        <el-date-picker type="datetime" format="YYYY/MM/DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                            v-model="formParam.dischargingTimeComms" placeholder="Please select" />
                    </el-form-item>
                </template>
            </el-table-column>
            <el-table-column prop="DRIFTING" label="TIME COMPL">
                <template #default="scope">
                    <el-form-item v-if="scope.$index==1" prop="loadingTimeCompl">
                        <el-date-picker type="datetime" format="YYYY/MM/DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                            v-model="formParam.loadingTimeCompl" placeholder="Please select" />
                    </el-form-item>
                    <el-form-item v-if="scope.$index==2" prop="dischargingTimeCompl">
                        <el-date-picker type="datetime" format="YYYY/MM/DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                            v-model="formParam.dischargingTimeCompl" placeholder="Please select" />
                    </el-form-item>
                </template>
            </el-table-column>
            <el-table-column prop="ATD" label="QUANTITY (PKGS)">
                <template #default="scope">
                    <el-form-item v-if="scope.$index==1" prop="loadingQuantity" style="width: 70%;margin: auto;">
                        <el-input-number v-model="formParam.loadingQuantity" placeholder="0.0" />
                    </el-form-item>
                    <el-form-item v-if="scope.$index==2" prop="dischargingQuantity" style="width: 70%;;margin: auto;">
                        <el-input-number v-model="formParam.dischargingQuantity" placeholder="0.0" />
                    </el-form-item>
                    <el-form-item v-if="scope.$index==4" prop="reHandlingQuantity" style="width: 70%;;margin: auto;">
                        <el-input-number v-model="formParam.reHandlingQuantity" placeholder="0.0" />
                    </el-form-item>
                </template>
            </el-table-column>
        </el-table>
    </el-form>

    <div class="pane-footer" v-hasPermi="['schedule:portOperation:edit']">
        <el-button @click="cancelHandle">{{ $t("ship.button.cancel") }}</el-button>
        <el-button type="primary" @click="submitForm" >{{ $t("ship.button.submit") }}</el-button>
    </div>
</template>
<script lang="ts" setup>
// @ts-nocheck
import { ref, onMounted, computed, reactive, nextTick, defineEmits } from "vue";
import service from "@/utils/request";
import { ElNotification, ElMessageBox } from "element-plus";
import {convertUrl} from "@/utils/tencentCos";
import DragUpload from '@/components/FormDataIUpload/index.vue';
import {hasTableEditAuth} from "@/utils/auth";
const props = defineProps({
    data: {
        type: Object,
        default: () => { },
    },
    portRotationId: {
        type: Number,
        default: 0
    },
    titleValue: {
        type: String,
        default: ''
    }
})
const emit = defineEmits(['saveOk','getDetail'])
const custForm = ref(null);
const formParam = ref({
    id: null,
    rampDownTime: null,
    rampUpTime: null,
    dischargingTimeComms: null,
    dischargingTimeCompl: null,
    loadingQuantity: null,
    loadingTimeComms: null,
    loadingTimeCompl: null,
    dischargingQuantity: null,
    reHandlingQuantity: null,
    portRotationId: props.portRotationId,
    damageReport: null,       
    damageReportFile: null,     //本地多文件上传

    voyageSof: null,
    voyageSofFile: null
})

const voyageSof = ref([])
const damageReport = ref([])
const processDamageReport = (damageReport) => {
    if (!damageReport) {
        return [];
    }
    return damageReport
        .split(",")            // 按逗号分割
        .map(item => item.trim())  // 去除首尾空格
        .filter(item => item && item !== "null"); // 过滤掉空字符串和 "null"
}
watch(
    () => props.data,
    val => {
    //判断一下val是不是非空对象
    if (Object.keys(val).length !== 0) {    
        formParam.value = Object.assign(val, {});
        if(formParam.value.voyageSof&&!formParam.value.voyageSof.name){
        voyageSof.value=[{name: getFileName(formParam.value.voyageSof),url:formParam.value.voyageSof}]
    }else{
        voyageSof.value=[]
    }
    if(formParam.value.damageReport){
        damageReport.value= processDamageReport(formParam.value.damageReport).map(item => ({name:getFileName(item),url:item}))
    }else{
        damageReport.value=[]
    }
    return;
}
},
{ deep: true, immediate: true }
);

let portInfoFormObj = ref({
    recordData: [{
        name: 'RAMP DOWN',
        ETA: null,
        ATA: null,
        ETD: null,
        ATD: '',
        ACTIVITY: '',
        VOYAGESOF: ''
    }, {
        name: 'LOADING',
        ETA: null,
        ATA: null,
        ETD: null,
        ATD: '',
        ACTIVITY: '',
        VOYAGESOF: ''
    }, {
        name: 'DISCHARGING',
        ETA: null,
        ATA: null,
        ETD: null,
        ATD: '',
        ACTIVITY: '',
        VOYAGESOF: ''
    }, {
        name: 'RAMP UP',
        ETA: null,
        ATA: null,
        ETD: null,
        ATD: '',
        ACTIVITY: '',
        VOYAGESOF: ''
    }, {
        name: 'RE-HANDLING',
        ETA: null,
        ATA: null,
        ETD: null,
        ATD: '',
        ACTIVITY: '',
        VOYAGESOF: ''
    }, {
        name: 'VOYAGE SOF',
        ETA: null,
        ATA: null,
        ETD: null,
        ATD: '',
        ACTIVITY: '',
        VOYAGESOF: ''
    }, {
        name: 'DAMAGE REPORT',
        ETA: null,
        ATA: null,
        ETD: null,
        ATD: '',
        ACTIVITY: '',
        VOYAGESOF: ''
    }]
})

const activitys = ["LOADING", "DISCHARGING", "BUNKERING", "D/D or SURVEY", "CREW CHANGE","PASSING"]
const rules = ref({});

const onFormValid = () => {
    nextTick(() => {
        formRef.value.validate()
    })
}
const submitForm = () => {
    // @ts-ignore
    custForm.value.validate(async (valid) => {
        if (!valid) {
            // @ts-ignore
            ElNotification.warning({
                title: "Prompt information",
                message: "verification not success！",
                position: "bottom-right",
            });
            return;
        }

        const formData = new FormData()
        for (const [k, n] of Object.entries(formParam.value)) {
            if (k === 'damageReportFile' && Array.isArray(n)) { 
                for (let i = 0; i < n.length; i++) {
                    formData.append("damageReportFile", n[i]); 
                }
            } else if (k === 'voyageSof') {
                if (n !== null && n !== undefined) {
                    formData.append("voyageSofFile", n);
                }
            } else {
                if (n) {
                    formData.append(k, n);
                }
            } 
        }
        await service.post("shipping/schedule/updatePortOperationRecord", formData);
        // @ts-ignore
        ElNotification.success({
            title: "Prompt information",
            message: "save successful!",
            position: "bottom-right",
        });
        cancelHandle()
    })
};
const cancelHandle = () => {
    voyageSof.value= []
    damageReport.value = []
    emit('saveOk')
}
const arraySpanMethod = ({
    row,
    column,
    rowIndex,
    columnIndex,
}) => {
    if (columnIndex === 1) {
        if (rowIndex === 5 || rowIndex === 6) {
            return [1, 4]
        }
    }
}
// 添加damageReportFile文件
const addDamageReportFile = (file) => {
    if(formParam.value.damageReportFile) {
        formParam.value.damageReportFile.push(file);
    } else {
        formParam.value.damageReportFile = [file];
    }
}
// 获取文件名称
function getFileName(name) { 
    if (name == null) {
        return name;
    } else if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
    } else {
        return name;
    }        
}

const handleVoyageSofFilesChange=(files)=> {
    formParam.value.voyageSof =files[0].file; 
}
const handleFileRemoved=(file,type)=> {
    if(file.url) {
        deleteFile(file,type,formParam)
    }
}
const deleteFile = (file,type) => { 
    let params = {id:type==0?formParam.value.portRotationId:formParam.value.id,type:type,url: file.url }
    service.post(`shipping/schedule/deleteFile`, params).then(res=>{
        ElNotification.success({
            title: "Prompt information",
            message: "Delete successful!",
            position: "bottom-right",
        });
        if(type === 1){
            damageReport.value= damageReport.value.filter(item => item.url !== file.url); 
        }
        if(type==0){
            voyageSof.value=[]
            formParam.value.voyageSof = null;
        }
        emit('getDetail',formParam.value.portRotationId)
    })
}
const handleDamageReportFilesChange=(files)=> {      
    addDamageReportFile(files[files.length-1].file)
}
</script>
<style>
    .el-table__expand-column .cell {
        display: none;
    }

    .c-expand {
        color: #888;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 700;
        cursor: pointer;
        width: 100%;
        height: 100%;
    }

    .c-expand i {
        font-size: 16px;
    }

    .c-expand i.expand {
        font-size: 16px;
        transform: rotate(90deg);
        transition: all 0.25s;
    }
</style>
<style lang="scss" scoped>
    ::v-deep(.el-table__header) {
        line-height: 48px !important;
        height: 48px;
    }

    .header-wrapper {
        border: 1px solid #ebeef5;
        border-bottom: none;
        padding: 10px;
    }

    .tips {
        text-align: right;

        .el-button {
            margin-left: 10px;
            margin-right: 15px;
        }
    }

    .pane-footer {
        margin-top: 20px;
        text-align: right;
    }
    .filestatus:hover {
        color: #409EFF;
        cursor: pointer;
        // text-decoration: underline;
    }
    /* 默认隐藏 X 按钮 */
        .delete-btn {
        // display: none;
        margin-left: 5px;
        cursor: pointer;
        // font-weight: bold;
        }
        .upload-wrapper{
            display: flex;
            border: 1px solid #d9d9d9;
            border-radius: 2px;
            line-height: 22px;
            padding: 0 5px;
            >span{
                color: #04a9eb;
                font-size: 24px;
                vertical-align: middle;
                margin-right: 2px;
                display: none;
            }
    }
    .upload-wrapper:hover{
    >span{
        display: block;
    }
    cursor: pointer;
    }
/* 悬浮时显示 X 按钮 */
//  
</style>